#_*_ coding: utf-8 _*_
import requests
import json
import os
import time
import logging
from datetime import datetime
from utils import synergism, zytoken,zymysql,userface


# 配置参数
RETRY_TIMES = 3  # 最大重试次数
DELAY_SECONDS = 7  # 默认延迟时间（秒）
Port = 4370
Password = ""  # 用户密码
Privilege = 0  # 用户权限：0为普通用户
Enabled = 1  # 用户启用标志：1为启用


# 设置日志配置
current_dir = os.path.dirname(os.path.abspath(__file__))
target_dir = os.path.join(os.path.dirname(current_dir), "logs")  # 子目录名称
log_filename = os.path.join(target_dir, "attendance_record.log")
logging.basicConfig(
    level=logging.INFO,  # 设置日志级别为INFO
    format='%(asctime)s - %(levelname)s - %(message)s',  # 设置日志格式
    handlers=[
        logging.FileHandler(log_filename),  # 将日志写入文件
        logging.StreamHandler()  # 也打印到控制台
    ]
)


# 获取表单信息
def StitchData(summaryid):
    url = 'http://192.168.0.13:4865/seeyon/rest/form/getformdata/' + str(summaryid)
    ZYtoken = zytoken.getzytoken()
    header = {"token": ZYtoken}
    try:
        req = requests.get(url, headers=header)
        result = req.json()  # 获得致远表单数据
        zhu = json.loads(result['DataJson'])[0]  # 主表字段
        print(zhu)
        devlistz = []
        devlist = tuple(zhu['field0003'].split(','))
        for dev in devlist:
            devname = \
            zymysql.seeyon_query("Select ctp_enum_item.showvalue from ctp_enum_item  where id="+str(dev))[0][0]
            devlistz.append(devname)
        ctpreference = zymysql.seeyon_query("SELECT FILE_URL,FILENAME from ctp_attachment WHERE SUB_REFERENCE="+str(zhu['field0005']))
        ctp_file_ID = ctpreference[0][0]  # 附件ID
        fileName = ctpreference[0][1]   # 文件名称
        dwEnrollNumber = zhu['field0002']   # 考勤号码
        token = zytoken.shen_header()['token']

        ctpurl = f'http://192.168.0.13:4865/seeyon/rest/attachment/file/{ctp_file_ID}?fileName={fileName}&token={token}'
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
            "Accept": "text/plain, */*; q=0.01",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Referer": "http://192.168.0.13:4865/seeyon/main.do",
        }
        # 发送 GET 请求
        response = requests.get(ctpurl, headers=headers)
        # 定义目标目录和路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        target_dir = os.path.join(os.path.dirname(current_dir), "upload")  # 子目录名称
        os.makedirs(target_dir, exist_ok=True)  # exist_ok=True 防止目录已存在时报错
        target_path = os.path.join(target_dir, fileName)  # 自动处理路径分隔符

        # 保存文件到指定目录
        with open(target_path, 'wb') as f:
            f.write(response.content)
        # 输出带完整路径的信息
        absolute_path = os.path.abspath(target_path)
        new_name = f"verify_biophoto_9_{dwEnrollNumber}.jpg"  # 新文件名
        renamefile = userface.rename_file(absolute_path, new_name)

        logging.info(f"成功获取表单数据: {zhu}---{devlistz}---{renamefile}")
        return zhu, devlistz, renamefile

    except Exception as e:
        logging.error(f"获取表单数据失败, summaryid: {summaryid}, 错误: {str(e)}")
        raise  # 重新抛出异常，以便在外层捕获并记录


def perform_operation(operation, operation_name, **kwargs):
    """执行操作并自动重试"""
    for attempt in range(1, RETRY_TIMES + 1):
        try:
            if operation(**kwargs):
                return
            print(f"{operation_name}失败，尝试 {attempt}/{RETRY_TIMES}")
        except Exception as e:
            print(f"{operation_name}异常: {str(e)}，尝试 {attempt}/{RETRY_TIMES}")

        if attempt < RETRY_TIMES:
            time.sleep(DELAY_SECONDS)
    raise


def process_device(ip, machine_num, enroll_num, Name, renamefile):
    """处理单个设备"""
    try:
        # 连接设备
        perform_operation(
            userface.connect_to_device, "连接设备",ip=ip, port=Port
        )

        # # 创建用户
        # perform_operation(
        #     userface.create_user, "创建用户",
        #     dwMachineNumber=machine_num, dwEnrollNumber= enroll_num,
        #     Name= Name, Password=Password, Privilege=Privilege, Enabled= Enabled
        # )

        # 上传人脸
        perform_operation(
            userface.send_user_face_photo, "上传人脸",
            machine_number=machine_num, file_name=renamefile
        )

        print("所有操作成功完成")

    except Exception as e:
        print(f"操作失败: {str(e)}")
        raise


def devicemain(zhu, devlistz, renamefile):
    Name = zhu['field0001']  # 用户姓名
    enroll_num = zhu['field0002']   # 考勤号码
    print(enroll_num)
    for entry in devlistz:
        try:
            ip, machine_num = entry.split(':')
            print(f"====== 处理设备 {ip} (机器号:{machine_num}) ======")
            process_device(ip, machine_num, enroll_num, Name, renamefile)

        except Exception as e:
            print(f"设备操作最终失败: {str(e)}")
        finally:
            time.sleep(DELAY_SECONDS)  # 设备间间隔


def insertusersql(zhu):
    Name = zhu['field0001']  # 用户姓名
    enroll_num = zhu['field0002']  # 考勤号码


    # 先查询用户是否已存在
    check_sql = "SELECT COUNT(*) FROM userinfo WHERE Badgenumber = %s"
    try:
        # 执行查询
        existing_count = zymysql.zkteco_query(check_sql, (enroll_num,))[0][0]
        if existing_count > 0:
            print(f"用户考勤号 {enroll_num} 已存在，跳过插入")
            return True  # 或者根据业务需求返回False
        else:
            insert_sql = "INSERT INTO userinfo (USERID, Badgenumber, SSN, Name, FSelected) VALUES (%s, %s, %s, %s, %s)"
            params_list = (enroll_num, enroll_num, '', Name, 0)
            inserted_count = zymysql.zkteco_execute(insert_sql, params_list)
            print(f"成功插入 {inserted_count} 条新记录")
            return True

    except Exception as e:
        print(f"操作出错: {e}")
        return False


def start(summaryid):
    try:
        zhu, devlistz, renamefile = StitchData(summaryid)
    except Exception as e:
        logging.error(f"获取表单数据失败, summaryid: {summaryid}, 错误: {str(e)}")
        # synergism.start(summaryid, False, "数据提取不成功:" + str(e))
        return  # 终止进一步操作

    # 考勤设备推送处理
    try:
        devicemain(zhu, devlistz, renamefile)
    except Exception as e:
        logging.error(f"推送创建失败, summaryid: {summaryid}, 错误: {str(e)}")
        # synergism.start(summaryid, False, f"推送创建失败, 请重新提交审批: {str(e)}")
        return  # 终止进一步操作

    # 更新考勤数据库
    try:
        insertsum = insertusersql(zhu)
        if insertsum:
            logging.info(f"更新处理完成，summaryid: {summaryid}")
        else:
            logging.error(f"更新创建失败, summaryid: {summaryid}")
    except Exception as e:
        logging.error(f"更新创建失败, summaryid: {summaryid}, 错误: {str(e)}")
        # synergism.start(summaryid, False, f"更新数据库失败, 请重新提交审批: {str(e)}")


if __name__ == '__main__':

    summaryid = "-1168982550868441025"
    start(summaryid)
